package com.atguigu.cloud.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.client.RestTemplate;

/**
 * @author bairimengchang
 * @version 1.0
 * @project cloud2024
 * @description RestTemplate是一种简单便捷的访问restful服务模板类，是Spring提供的用于访问Rest服务的客户端模板工具集
 * @date 2024/9/12
 */
@Configuration
// 远程调用时，使用RestTemplateConfig类配置的负载均衡策略，默认为轮询策略RoundRobinLoadBalancer
@LoadBalancerClient(value = "cloud-payment-service",configuration = RestTemplateConfig.class)
public class RestTemplateConfig {

    // RestTemplate（更方便） 和 HttpClient（更底层） 在本质上都是用来发送 HTTP 请求并接收响应的工具
    @Bean
    @LoadBalanced       // 必须配置负载均衡
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    // 创建并返回一个ReactorLoadBalancer类型的随机负载均衡器
    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }

}
